import React, { useState } from 'react';
import { useColorStore } from '@/stores';
import { ColorPicker } from '@/components/color/ColorPicker';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { Input } from '@/components/ui/Input';
import { ColorUtils } from '@/utils/color';
import { copyToClipboard } from '@/utils';

export const ColorPickerPage: React.FC = () => {
  const {
    currentColor,
    selectedColors,
    pickerMode,
    setCurrentColor,
    addSelectedColor,
    removeSelectedColor,
    updateSelectedColor,
    clearSelectedColors,
    setPickerMode,
    createPalette,
    generateRandomPalette,
    exportPalette
  } = useColorStore();

  const [showSaveModal, setShowSaveModal] = useState(false);
  const [showExportModal, setShowExportModal] = useState(false);
  const [paletteName, setPaletteName] = useState('');
  const [exportFormat, setExportFormat] = useState<'json' | 'css' | 'sass'>('json');

  const handleSavePalette = async () => {
    if (!paletteName.trim()) {
      alert('请输入调色板名称');
      return;
    }

    try {
      await createPalette(paletteName, 'custom');
      setShowSaveModal(false);
      setPaletteName('');
      alert('调色板保存成功！');
    } catch (error) {
      alert(error instanceof Error ? error.message : '保存失败');
    }
  };

  const handleExport = () => {
    try {
      const exportData = exportPalette(exportFormat);
      const filename = `palette-${Date.now()}.${exportFormat === 'json' ? 'json' : 'css'}`;
      
      // 创建下载链接
      const blob = new Blob([exportData], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      link.click();
      window.URL.revokeObjectURL(url);
      
      setShowExportModal(false);
    } catch (error) {
      alert(error instanceof Error ? error.message : '导出失败');
    }
  };

  const handleCopyColor = async (color: any) => {
    const success = await copyToClipboard(color.hex);
    if (success) {
      alert(`颜色 ${color.hex} 已复制到剪贴板`);
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">色彩选择器</h1>
          <p className="text-gray-600">选择和调整颜色，创建你的专属调色板</p>
        </div>
        <div className="flex items-center space-x-2">
          <Button
            variant="outline"
            onClick={() => setPickerMode(pickerMode === 'simple' ? 'advanced' : 'simple')}
          >
            {pickerMode === 'simple' ? '高级模式' : '简单模式'}
          </Button>
          <Button onClick={generateRandomPalette}>
            🎲 随机生成
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 色彩选择器 */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-lg shadow-md p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">颜色选择</h2>
            <ColorPicker
              value={currentColor.hex}
              onChange={setCurrentColor}
              mode={pickerMode === 'simple' ? 'hex' : 'hsl'}
              showPresets={true}
            />

            {/* 当前颜色信息 */}
            <div className="mt-6 p-4 bg-gray-50 rounded-lg">
              <h3 className="text-sm font-medium text-gray-700 mb-3">当前颜色信息</h3>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">HEX:</span>
                  <span className="font-mono">{currentColor.hex}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">RGB:</span>
                  <span className="font-mono">
                    {currentColor.rgb.r}, {currentColor.rgb.g}, {currentColor.rgb.b}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">HSL:</span>
                  <span className="font-mono">
                    {currentColor.hsl.h}°, {currentColor.hsl.s}%, {currentColor.hsl.l}%
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">温度:</span>
                  <span>{ColorUtils.getTemperature(currentColor) === 'warm' ? '暖色' : ColorUtils.getTemperature(currentColor) === 'cool' ? '冷色' : '中性'}</span>
                </div>
              </div>
              
              <div className="mt-4 flex space-x-2">
                <Button
                  size="sm"
                  onClick={() => addSelectedColor(currentColor)}
                  className="flex-1"
                >
                  添加到调色板
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => handleCopyColor(currentColor)}
                >
                  复制
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* 调色板 */}
        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900">
                当前调色板 ({selectedColors.length}/10)
              </h2>
              <div className="flex space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={clearSelectedColors}
                  disabled={selectedColors.length === 0}
                >
                  清空
                </Button>
                <Button
                  size="sm"
                  onClick={() => setShowSaveModal(true)}
                  disabled={selectedColors.length === 0}
                >
                  保存
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowExportModal(true)}
                  disabled={selectedColors.length === 0}
                >
                  导出
                </Button>
              </div>
            </div>

            {selectedColors.length > 0 ? (
              <div className="space-y-4">
                {/* 调色板预览 */}
                <div className="grid grid-cols-5 md:grid-cols-10 gap-2">
                  {selectedColors.map((color, index) => (
                    <div
                      key={index}
                      className="aspect-square rounded-lg border border-gray-300 cursor-pointer group relative overflow-hidden"
                      style={{ backgroundColor: color.hex }}
                      onClick={() => handleCopyColor(color)}
                      title={`点击复制 ${color.hex}`}
                    >
                      {/* 删除按钮 */}
                      <button
                        className="absolute top-1 right-1 w-4 h-4 bg-red-500 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity"
                        onClick={(e) => {
                          e.stopPropagation();
                          removeSelectedColor(index);
                        }}
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>

                {/* 详细列表 */}
                <div className="space-y-2">
                  {selectedColors.map((color, index) => (
                    <div
                      key={index}
                      className="flex items-center space-x-4 p-3 bg-gray-50 rounded-lg"
                    >
                      <div
                        className="w-12 h-12 rounded border border-gray-300"
                        style={{ backgroundColor: color.hex }}
                      />
                      <div className="flex-1">
                        <div className="flex items-center space-x-4">
                          <span className="font-mono text-sm">{color.hex}</span>
                          <span className="text-sm text-gray-600">
                            RGB({color.rgb.r}, {color.rgb.g}, {color.rgb.b})
                          </span>
                          <span className="text-sm text-gray-600">
                            HSL({color.hsl.h}°, {color.hsl.s}%, {color.hsl.l}%)
                          </span>
                        </div>
                        <div className="text-xs text-gray-500 mt-1">
                          {ColorUtils.isLight(color) ? '浅色' : '深色'} · 
                          {ColorUtils.getTemperature(color) === 'warm' ? '暖色调' : 
                           ColorUtils.getTemperature(color) === 'cool' ? '冷色调' : '中性色调'}
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => setCurrentColor(color.hex)}
                        >
                          编辑
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCopyColor(color)}
                        >
                          复制
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => removeSelectedColor(index)}
                        >
                          删除
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="text-center py-12">
                <div className="text-gray-400 mb-4">
                  <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4z" />
                  </svg>
                </div>
                <h3 className="text-lg font-medium text-gray-900 mb-2">调色板为空</h3>
                <p className="text-gray-600 mb-4">选择颜色并点击"添加到调色板"开始创建</p>
                <Button onClick={() => addSelectedColor(currentColor)}>
                  添加当前颜色
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 保存调色板模态框 */}
      <Modal
        isOpen={showSaveModal}
        onClose={() => setShowSaveModal(false)}
        title="保存调色板"
      >
        <div className="space-y-4">
          <Input
            label="调色板名称"
            value={paletteName}
            onChange={setPaletteName}
            placeholder="输入调色板名称"
          />
          <div className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setShowSaveModal(false)}
            >
              取消
            </Button>
            <Button onClick={handleSavePalette}>
              保存
            </Button>
          </div>
        </div>
      </Modal>

      {/* 导出模态框 */}
      <Modal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        title="导出调色板"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              导出格式
            </label>
            <select
              value={exportFormat}
              onChange={(e) => setExportFormat(e.target.value as any)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="json">JSON</option>
              <option value="css">CSS 变量</option>
              <option value="sass">SASS 变量</option>
            </select>
          </div>
          <div className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setShowExportModal(false)}
            >
              取消
            </Button>
            <Button onClick={handleExport}>
              导出
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};